Exercises

Please complete each exercise or answer the question before reviewing the posted solution comments.

  1. Write an algorithm in pseudocode (that uses a for loop) that will create the following matrix: 11x11 matrix with 1s on the diagonal like the identity matrix and -1/2 before and after each 1 on rows 2 through 10

    
        declare a variable and set it to an 11x11 identity matrix
        for each row r from 2 to 10
            set the value at the current row r and the columns r-1 and r+1 to -1/2

    A for loop is a natural choice for this type of problem because we know how many times it must execute and for which values.

  2. Write an algorithm in pseudocode (that uses a for loop) that will create a matrix like that in exercise one where all you know is the value of N, where N is the number of rows and columns in the matrix. Otherwise, it follows the same pattern as shown in the previous matrix.

    
        get N from somewhere (the user, a file, a function parameter value)
        if N is a positive integer
            for each row r from 2 to N-1
                set the value at the current row r and the columns r-1 and r+1 to -1/2

    Once we check that N is a positive integer, we can still use a for loop for this solution even though we don't know the value of N because our code will have the value of N at runtime, the point in time that the code is actually executed.

  3. Write an algorithm in pseudocode to display the first 10 terms in the fibonacci series.

    Note: The Fibonacci series start with the values 1 and 2 and then each new value is the sum of the two previous values.

    Fibonacci Series: 1, 2, 3, 5, 8, 13, 21, 34, ...

    
        declare a matrix variable to hold the series values
        initialize the series with the values 1 and 2
        for values 3 through 10
            add the last two values in the series together
            place that sum as the next value in the series